<?php

/*
References: 
============
https://gist.github.com/kevlened/fc89bd6a8cf22b36cc34ff9292e4c8bc
https://www.labnol.org/code/19011-google-analytics-php
https://developers.google.com/analytics/devguides/collection/protocol/v1/devguide
*/

require_once('classes/class.logger.php');
require_once('classes/class.http.php');
require_once('classes/class.request.php');
require_once('libs/functions.php');

$httpObj = new HttpCall;
$httpObj->setCacheTime(3600);
$logger = new Logger('./logs/', 10);

$urls_to_proxy = [
    // these strings will be replaced by a unique proxy url
    'www.google-analytics.com',
    'ampcid.google.com/v1/publisher',
    'www.google-analytics.com',
    'www.googletagmanager.com',
    'stats.g.doubleclick.net'
];

$replacements = [
    // if key is found, it is replaces by the value
    '.gif?' => '.iiiii?',
    '/collect' => '/bbbbb'
];

$headers_to_forward = [
    // these headers will be forwarded in the call action. Key is the Server Variable of the request, Value is the Curl Header variable
    'HTTP_REFERER' => 'Referer',
    'HTTP_ACCEPT' => 'Accept',
    'HTTP_ACCEPT_CHARSET' => 'Accept-Charset',
    'HTTP_ACCEPT_ENCODING' => 'Accept-Encoding',
    'HTTP_ACCEPT_LANGUAGE' => 'Accept-Language',
    'HTTP_USER_AGENT' => 'User-Agent',
];

/*
$inject_ip = [
    // if key is found, the ip address is inserted using the value as name
    '_utma' => '_utmip'
]
*/
//var_dump($httpObj->cached('https://ranner.de/echo.php', 'POST', ['aaa'=>123])); 
//var_dump($httpObj->cached('https://www.google.de', 'GET', ['aaa'=>123])); 

if(Request::getPath(0) == 'file') {

    $file = false;

    if (Request::getPath(1) == 'g-a-legacy.js') {
        $file = $httpObj->cached('https://ssl.google-analytics.com/ga.js');
    }
    
    if (Request::getPath(1) == 'g-a.js') {
        $file = $httpObj->cached('https://www.google-analytics.com/analytics.js');
    }
    
    if (Request::getPath(1) == 't-m.js') {
        $file = $httpObj->cached('https://www.googletagmanager.com/gtm.js', 'GET', ['id' => Request::get('id')]);
    }
    
    if (Request::getPath(1) == 'd-c.js') {
        $file = $httpObj->cached('https://stats.g.doubleclick.net/dc.js');
    }

    if ($file) {
        $logger->log(Request::getPath(1), false);
        header('content-type: ' . $file['headers']['content-type'], true);
        $content = $file['content'];
        $content = replaceUrls($content, $urls_to_proxy, Request::baseUrl() . 'call/');
        $content = replaceStrings($content, $replacements);
        die($content);
    } else {
        http_response_code(404);
        $logger->error('404 - The file ' . htmlspecialchars(Request::getPath(1)) . ' was not found on the server.');
        die();
    }

}

if(Request::getPath(0) == 'call') {
    
    $url_id = Request::getPath(1);
    if(is_numeric($url_id) && isset($urls_to_proxy[$url_id])) {

        $url = $urls_to_proxy[$url_id];
        $furtherPath = Request::getPathString(2);
        if($furtherPath!='') $url .= '/' . $furtherPath; 
        $queryString = Request::getenv('QUERY_STRING');
        if($queryString !== false && $queryString !== '') {
            $url .= '?' . $queryString;
        }
        $url = unreplaceStrings($url, $replacements);
        if(substr($url, 0, 2) == '//') {
            $url = 'https:' . $url;
        }
        if(substr($url, 0, 8) != 'https://' && substr($url, 0, 7) != 'http://') {
            $url = 'https://' . $url;
        }

        foreach($headers_to_forward As $k => $v) {
            if(Request::getenv($k)) {
                $httpObj->add_curlRequestHeader([$v => Request::getenv($k)]);
            }
        }

        if(count(Request::post()) > 0) {
            $data = Request::post();
            $data['uip'] = Request::getClientIp();
            $response = $httpObj->call($url, 'POST', $data);
            $logger->log('POST to ' . $url, false);
            $logger->debug('POST to ' . $url . "\r\n" . var_export($data, true), false);
        } else {
            if(!getQueryFromUrl($url, 'uip')) {
                $url .= (strpos($url, '?') === false ? '?' : '&') . 'uip=' . Request::getClientIp();
            }
            foreach(getQueryFromUrl($url) As $k => $v) {
                if(stripos($v, 'dont-block')!==false && isset($_SERVER['HTTP_REFERER'])) {
                    $url = replaceGetVarInUrl($url, $k, $_SERVER['HTTP_REFERER']);
                }
            }
            $url = replaceGetVarInUrl($url, 'dt', '>> ' . getQueryFromUrl($url, 'dt')); // Markierung um die gewonnenen Zugriffe in Analytics zu erkennen. TODO: bessere Möglichkeit?
            $response = $httpObj->call($url, 'GET');
            $logger->log('GET from ' . $url, false);
            $logger->debug('GET from ' . $url . "\r\n" . var_export($response, true), false);
        }

        http_response_code(
            $response['headers']['http_code_numeric']
        );

        foreach($response['headers'] As $k => $v) {
            header($k . ': ' . $v);
        }

        $content = $response['content'];
        $content = replaceUrls($content, $urls_to_proxy, Request::baseUrl() . 'call/');
        $content = replaceStrings($content, $replacements);

        $logger->debug('Result from ' . $url . ' :' . "\r\n" . $content, false);
        if(count($httpObj->getErrors()) > 0) {
            $logger->debug([$httpObj->getErrors(), $response], false);
        }
        
        die($content);

    } else {
        http_response_code(400);
        $logger->error('400 - Bad request');
        die();
    }

}

http_response_code(400);
$logger->error('400 - Bad request');
die();

